package com.zhuotiao.crm.service.demo;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import com.pikachu.web.pojo.PageBean;
import com.zhuotiao.crm.mapper.DemoMapper;
import com.zhuotiao.crm.model.dto.DemoEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author huang_kangjie
 * @create 2018-08-28 10:19
 **/
@Service
public class IDemoService {

     private final DemoMapper demoMapper;


     @Autowired
     public IDemoService(DemoMapper demoMapper) {
          this.demoMapper = demoMapper;
     }

     public int addDemo(DemoEntity entity) {
          return this.demoMapper.insertSelective(entity);
     }

     public int delDemo(Long id) {
          return this.demoMapper.deleteByPrimaryKey(id);
     }

     public int updateDemo(DemoEntity entity) {
          return this.demoMapper.updateByPrimaryKeySelective(entity);
     }

     /**
      * 根据tk查询
      * @param id
      * @return
      */
     public DemoEntity selelctOne(long id){
          Example example = new Example(DemoEntity.class);
          example.createCriteria().andEqualTo("id", id);
          return this.demoMapper.selectOneByExample(example);
     }

     /**
      * 查询xml里面sql
      * @return
      */
     public List<DemoEntity> getListXML() {
          return this.demoMapper.getListByXML();
     }

     /**
      * 分页查询
      * @param pageBean
      * @param param
      * @return
      */
     public PageInfo<DemoEntity> page(PageBean pageBean, String param) {
          PageHelper.startPage(pageBean.getPageNo(), pageBean.getPageSize());
          Example example = new Example(DemoEntity.class);
          if(!StringUtils.isEmpty(param)) {
               example.createCriteria().andEqualTo("demo", param);
          }
          List<DemoEntity> list = this.demoMapper.selectByExample(example);
          PageInfo<DemoEntity> pageinfo = new PageInfo<>(list);
          return pageinfo;
     }


     /**
      * 分页查询
      * @param pageBean
      * @param param
      * @return
      */
     public Page<List<DemoEntity>> selectPage(PageBean pageBean, String param){
          int p = Preconditions.checkNotNull(pageBean.getPageNo());
          int r = Preconditions.checkNotNull(pageBean.getPageSize());
          Example example = new Example(DemoEntity.class);
          if(!StringUtils.isEmpty(param)) {
               example.createCriteria().andEqualTo("demo", param);
          }
          return PageHelper.startPage(p, r).doSelectPage(() -> this.demoMapper.selectByExample(example));
     }
}
